package com.persistencia.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.exceptions.PersistenceException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class RecordStringFile extends RecordStrategy {
	private Gson gson;

	public RecordStringFile(Class<?> classType) throws PersistenceException {
		super(classType);
		try {
			gson = new Gson();
			FILE_NAME += getClassTypeName() + ".txt";
			createFile();
		} catch (Exception e) {
			throw new PersistenceException(e);
		}

	}

	@Override
	public synchronized Boolean writeData(List<?> obj)
			throws PersistenceException {

		try {
			String jsonOutput = gson.toJson(obj);
			BufferedWriter out = new BufferedWriter(new FileWriter(FILE_NAME));
			out.write(jsonOutput);
			out.close();

		} catch (Exception e) {
			throw new PersistenceException(e);
		}
		return true;
	}

	@Override
	public synchronized List<?> readData() throws PersistenceException {
		List<Object> list = new ArrayList<Object>();
		StringBuffer buffer = new StringBuffer();
		String line;
		FileReader fReader;
		BufferedReader bReader;

		try {
			fReader = new FileReader(FILE_NAME);
			bReader = new BufferedReader(fReader);
			while ((line = bReader.readLine()) != null) {
				buffer.append(line);
			}
			bReader.close();
			fReader.close();
			String dataString = buffer.toString();
			Type collectionType = new TypeToken<List<Object>>() {
			}.getType();
			list = gson.fromJson(dataString, collectionType);

		} catch (Exception e) {
			throw new PersistenceException(e);
		}

		return list;
	}

}
